<template>
  <div class="course-editor">
    <h2>{{ isEdit ? '编辑课程' : '添加课程' }}</h2>
    <el-form :model="courseForm" label-width="100px">
      <el-form-item label="课程ID">
        <el-input v-model="courseForm.id" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="教师ID">
        <el-input v-model="courseForm.teaId"></el-input>
      </el-form-item>
      <el-form-item label="课程名称">
        <el-input v-model="courseForm.couName"></el-input>
      </el-form-item>
      <el-form-item label="课程简介">
        <el-input type="textarea" v-model="courseForm.couIntroduction"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveCourse">{{ isEdit ? '更新' : '保存' }}</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { teacherApi } from '@/api/teacher'

const route = useRoute()
const router = useRouter()

const isEdit = !!route.params.id
const courseForm = reactive({
  id: '',
  teaId: '',
  couName: '',
  couIntroduction: ''
})

// 获取课程信息
const fetchCourse = async () => {
  if (isEdit) {
    // 实际项目中应该调用获取课程详情的API
    // 这里简化处理
    const response = await teacherApi.getTeacherByUid(1) // 假设当前用户ID为1
    const teacher = response.data
    courseForm.teaId = teacher.id
    courseForm.couName = `课程${Math.floor(Math.random() * 100)}`
    courseForm.couIntroduction = `课程简介${Math.floor(Math.random() * 100)}`
  }
}

// 保存课程
const saveCourse = async () => {
  try {
    if (isEdit) {
      // 实际项目中应该调用更新课程API
      ElMessage.success('课程更新成功')
    } else {
      // 实际项目中应该调用保存课程API
      ElMessage.success('课程添加成功')
    }
    router.push('/class/courses/1') // 返回课程列表
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 取消编辑
const cancel = () => {
  router.push('/class/courses/1') // 返回课程列表
}

// 初始化
fetchCourse()
</script>